# -*- coding: utf-8 -*-
from os.path import join
from ..shortcuts import *
from urllib import quote
from accost.utils.handlers import serve_static


@home.expose("/static/<path:path>", methods=["GET"])
def staticApp():
    return serve_static(join(base_path, "static"))


@home.expose("/login/")
def login():
    if request.method == "GET":
        return render("login.html")
    username = self.request.form.get('username', u'').strip()
    password = self.request.form.get('password', u'').strip()
    user = session.query(User).filter(username==username).first()
    if not user:
        return error(u"用户名或密码错误")
    if not user.checkPassword(password):
        return error(u"用户名或密码错误")
    user.login(self.request)
    response = success(u"登录成功")
    response.set_cookie("name", quote(user.name.encode("utf-8")))
    return response


@home.expose("/logout/")
def logout():
    request.logout()
    response = redirect('/')
    response.delete_cookie("name")
    return response
